package cn.com.callback

import cn.com.kh.KHUtil
import com.alibaba.fastjson.JSONObject
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import cn.com.callback.ServiceBackInvoke
import cn.com.elite.EliteBean

import java.text.SimpleDateFormat;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory

/**
 *
 * @Title: aipHSTCustomerLable* @Description:华盛证券 将导入的客户 按指定的人均分分配 --内部接口
 * @author: chieh* @date 2021-12-24 16:32:00
 *
 */

public class aipHSTCustomerLable implements ServiceBackInvoke {
    private static final Log log = LogFactory.getLog(aipHSTCustomerLable.class);

    public String doCallBack(EliteBean eliteBean, HttpServletRequest request, HttpServletResponse response) {
        response.setCharacterEncoding("UTF-8");

        String getMethod = request.getMethod();

        log.debug("getMethod:" + getMethod);
        long endTime;
        String inData = "";
        String outData = "";
        String dataSourceID = "dataSource";

        BufferedReader iny = null;
        if (getMethod.equals("GET")) {
            inData = request.getParameter("data");
            log.debug("原始Get请求参数:" + inData);
        } else {
            InputStreamReader reader = new InputStreamReader(request.getInputStream(), "UTF-8");
            iny = new BufferedReader(reader);
            String line;
            while ((line = iny.readLine()) != null) {
                inData += line;
            }
            log.debug("原始Post请求参数:" + inData);
        }

        try {
            long startTime = System.currentTimeMillis();

            // 调用处理信息
            JSONObject inObject = JSONObject.parseObject(inData);
            log.debug("处理前的Json：" + inObject.toString());
            def batchid = inObject.getString("batchid");//批次id

            log.debug("解析信息-" + "batchid: " + batchid);
            if (batchid != '' && batchid != null) {
                outData = allocationData(eliteBean, batchid, inObject, dataSourceID);
            } else {
                log.error("处理失败(批次号为空错误)!");
                endTime = System.currentTimeMillis();
                return "{\"resultcode\":\"0\",\"resultmessage\":\"处理失败(批次号为空错误),调用问题处理时长(毫秒):" + (endTime - startTime) + "\",\"data\":[]}";
            }

        } catch (Exception e) {
            log.error("接口处理异常" + e.getMessage());
            outData = "{\"resultcode\":\"0\",\"resultmessage\":\"处理失败(" + e.getMessage() + ")\",\"data\":[]}";
        }

        log.debug("完成返回结果:" + outData);

        return outData;
    }

    // 处理开发名单任务
    public static String allocationData(EliteBean eliteBean, String batchid, JSONObject inObject, String dataSourceID) {

        long startTime = System.currentTimeMillis();
        long endTime = System.currentTimeMillis();
        JSONObject resultJson = new JSONObject();
        SimpleDateFormat dateformat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        log.debug("startTime" + startTime);

        //   try {

        //循环捞取当前批次的任务
        def selectcustomerlabelSQL = "select DISTINCT hsid from hst_customerlabel_details where batch_id='" + batchid + "'";
        //获取本批客户标签ID
        def selectlabelbacthSQL = "select lable_id as lableid from hst_customerlabel_bacth where batch_id='" + batchid + "'";

        log.debug("查询分配数量selectmarketing_temporarySQL=" + selectcustomerlabelSQL);
        List selectmarketing_temporaryList = eliteBean.chaxun_sql(selectcustomerlabelSQL, "dataSource");
        List selectlabelbacthList = eliteBean.chaxun_sql(selectlabelbacthSQL, "dataSource");
        log.debug("selectlabelbacthList=" + selectlabelbacthList);

        String labeid = selectlabelbacthList.get(0).get("lableid"); //获取hst_customerlabel_bacth批次表的便签ID
        log.debug("labeid=" + labeid);
        def ListNum = selectmarketing_temporaryList.size();
        log.debug("待分配ListNum=" + ListNum);
/*
            int arrInt = 100;
            //轮询分配次数
            double number = ListNum * 1.0 / arrInt;
            log.debug("轮询分配次数number :" + number);
            //轮询次数向上取整
            int count=Math.ceil(number);
          //  int count = Math.floor(number);

            log.debug("轮询次数取整count :" + count);
            int yscount = ListNum % arrInt;
            log.debug("yscount :" + yscount);
*/
        String[] insertSQL = new String[ListNum];
        int m = 0;
        int n = 0;
        int arrInt = 100;
        //轮询分配次数
        double number = ListNum * 1.0 / arrInt;
        log.debug("轮询分配次数number :" + number);
        //轮询次数向上取整
        int count = Math.ceil(number);
        log.debug("轮询次数取整count :" + count);
        int yscount = ListNum % arrInt;
        log.debug("yscount :" + yscount);
        for (int j = 0; j < ListNum; j++) {
            String hsid = selectmarketing_temporaryList.get(j).get("hsid");  //从hst_customerlabel_details详情表获取每一个华盛号
            def getobjecitiveSelectSQL = eliteBean.chaxun_sql("select   objective_guid	as objectiveGuid from objective where MAP_ID='MY48ZX' and  customer_guid  in (select  customer_guid  from customer where  customer_id='" + hsid + "')", "dataSource")
            if (getobjecitiveSelectSQL.size() > 0) {
                String objective_guid = getobjecitiveSelectSQL.get(0).get("objectiveGuid");
                //从objective表中获取华盛号客户对应的objective_guid
                def getcustomerlabeloSelectSQL = eliteBean.chaxun_sql("select RELATION_GUID from customerlabelo where RELATION_GUID='" + objective_guid + "'and RELATION_LABELID='" + labeid + "'", "dataSource");
                if (getcustomerlabeloSelectSQL.size() <= 0) {
                    log.debug("添加数据");
                    // Map selectmarketing_temporarySQLMAP = selectmarketing_temporaryList.get(m);
                    insertSQL[j] = "insert into customerlabelo (RELATION_GUID,RELATION_LABELID,CREATEDBY,CREATEDDATE) values('" + objective_guid + "','" + labeid + "','SELETE',now()) ";
                }else{
                    insertSQL[j]=null;
                }
            }
            m++;
            log.debug("前：这是第"+n+"次数据=======第"+m+"");

            if (m == arrInt || (n == count - 1 && m == yscount)) {
                log.debug("这是第"+n+"次数据");
                log.debug(insertSQL.toString());
                //将数据插入数据库
                int[] customerguidsqlResult = eliteBean.updateBatch(insertSQL, dataSourceID);
                log.debug("提交数据库操作SQL结果:" + customerguidsqlResult.toString());
                insertSQL = new String[ListNum];
                m = 0;
                n++;
            }
        }

        // 生成处理完成时间
        endTime = System.currentTimeMillis();

        //将批次状态修改成已完成
        // 包装拼接返回JSONObject
        resultJson.put("resultcode", 1);
        resultJson.put("resultmessage", "处理完成,调用问题处理时长(毫秒):" + (endTime - startTime));
        //  } catch (Exception e) {
        //     endTime = System.currentTimeMillis();
        //     resultJson.put("resultcode", 4);
        //    resultJson.put("resultmessage", "处理失败:(" + e.getMessage() + ")" + "处理完成,调用问题处理时长(毫秒):" + (endTime - startTime));
//
        //   }

        return resultJson.toString();
    }

    // 解析Json值
    public static String GetJV(JSONObject inJson, String getKey) {
        String Rev_Value = null;
        try {
            Rev_Value = inJson.getString(getKey);
        } catch (Exception e) {
            try {
                Rev_Value = String.valueOf(inJson.getInt(getKey));
            } catch (Exception e1) {
                try {
                    Rev_Value = String.valueOf(inJson.getJSONArray(getKey));
                } catch (Exception e2) {
                    try {
                        Rev_Value = String.valueOf(inJson.getJSONObject(getKey));
                    } catch (Exception e3) {
                        Rev_Value = "";
                    }
                }
            }
        } finally {
            if (Rev_Value == null || Rev_Value.equals("null") || Rev_Value.length() <= 0) {
                Rev_Value = "";
            } else {
            }
        }
        log.debug("解析-k=" + getKey + " v=" + Rev_Value);
        return Rev_Value;
    }

}
